package com.thread.sync.sync03;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现一个线程往数组添加元素,另一个线程监听,当元素为5的时候停止这个线程
 */
public class ListAdd01 {
    private volatile static List list = new ArrayList();

    public void addList() {
        list.add("houzheng");
    }

    public int getSize() {
        return list.size();
    }

    public static void main(String[] args) {
        final ListAdd01 list01 = new ListAdd01();
        //t1,添加元素
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        list01.addList();
                        System.out.println(Thread.currentThread().getName() + " : " + list01.getSize());
                        Thread.sleep(500);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();
        //t2监听,性能消耗比较大,得不停判断
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (list01.getSize() == 5) {
                        System.out.println("t1添加的元素达到5,线程t2停止!");
                        throw new RuntimeException();
                    }
                }
            }
        }, "t2").start();

    }

}
